﻿using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using MyFloridaHouse.DataAccess;
using MyFloridaHouse.libSvDTO;
using Microsoft.SqlServer.Types;
using MyFloridaHouse.DataAccess.Extensions;
using SQLSpatialTools;
using System.Data.SqlTypes;
using System.Text;

namespace MyFloridaHouse.libServiceBusinessRules
{
    public static class DistrictShapeBuilder
    {
        /// <summary>
        /// Builds the district using SqlGeometry.
        /// </summary>
        /// <param name="geometryList">The geometry list.</param>
        /// <returns><see cref="SqlGeometry"/></returns>
        public static SqlGeometry BuildDistrict(List<SqlGeometry> geometryList)
        {

            List<SqlGeometry> iGeometryList;
            iGeometryList = geometryList;
            SqlGeometry geom = new SqlGeometry();
            GeometryCollectionAggregate CollAggregate = new GeometryCollectionAggregate();
            CollAggregate.Init();
            for (int listIndex = 0; listIndex < geometryList.Count; )
            {
                CollAggregate.Accumulate(geometryList[listIndex]);
                listIndex++;
            }
            geom = CollAggregate.Terminate();
            geom = geom.STUnion(geom);

            SqlGeometry iGeom = new SqlGeometry();
            iGeom = geom;

            List<Polygon> polygons = PolygonTools.GetPolygons(geom, 20);
            List<Polygon> polygonsCleaned = PolygonTools.CleanPolygons(polygons);
            SqlGeometry newGeom = SQLGeometryTools.CreateNewGeomFromReducedShape(polygonsCleaned);
            geom = newGeom.MakeValid();

            if ((geom.STGeometryType() == "POLYGON")) //filter artifacts doesn't seem to handle multipolys
            {
                // TODO:  This is removing valid interior rings, so disable till function is fixed
                //geom = Functions.FilterArtifactsGeometry(geom, true, true, 100, .08);
            }

            if (geom.IsNull) //SpatialTools's sent back a null
            {
                geom = SQLGeometryTools.UnionSQLGeometries(iGeometryList);
                //geom = Functions.FilterArtifactsGeometry(geom, true, true, 100, .08);
            }
            //Filter Artifacts returned an empty object so we will
            //remove slivers the old fashioned way
            if (geom.ToString().Contains("EMPTY"))
            {
                //geom = iGeom.BufferWithTolerance(1, 1, true).BufferWithTolerance(-2 * 1, 1, true).STUnion(iGeom); //this times out...
                //geom = RemoveSlivers(iGeom); //this doesn't hand small blocks... 
                geom = iGeom;
            }
            return geom;
        }

    }
}
